import axios from "axios"
import { ElMessage } from "element-plus"
// 引入pinia中user模块
import useUserStore from "@/store/modules/user"

const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API, //请求的路径加上基础路径
    timeout: 5000, //超时时间
})

// 请求拦截
request.interceptors.request.use((config) => {
    // 还可以配置请求头...

    // 调用方法
    const userStore = useUserStore()
    // 设置请求头
    config.headers["token"] = userStore.token
    // 返回配置对象
    return config
})

// 响应拦截
request.interceptors.response.use(
    (response) => {
        // 成功的回调
        // 简化数据
        return response.data
    },
    (error) => {
        // 失败的回调
        // 处理 http 网络提示
        let msg = ""
        let status = error.response.status
        switch (status) {
            case 401:
                msg = "未授权，请重新登录"
                break
            case 403:
                msg = "拒绝访问"
                break
            case 404:
                msg = "请求错误，未找到该资源"
                break
            case 405:
                msg = "请求方法未允许"
                break
            case 500:
                msg = "服务器端出错"
                break
            case 502:
                msg = "网络错误"
                break
            case 503:
                msg = "服务不可用"
                break
            case 504:
                msg = "网络超时"
                break
            default:
                msg = "连接错误" + status
        }
        ElMessage({
            type: "error",
            message: msg,
        })
        return Promise.reject(error)
    }
)

export default request
